<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blogwebpage/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blogwebpage/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/blogwebpage/images/favicon.ico">
  <link rel="mask-icon" href="/blogwebpage/images/logo.svg" color="#222">
  <meta name="msvalidate.01" content="9BDlx6FiNE">

<link rel="stylesheet" href="/blogwebpage/css/main.css">


<link rel="stylesheet" href="/blogwebpage/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangkejie.gitee.io","root":"/blogwebpage/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="iOS App程序崩溃的抓取与分析 备用: xun开源代码地址   Mach异常捕获方式 mach_port_allocate 创建一场端口 mach_port_insert_right 申请 set_exception_ports 的权限 xxx_set_exception_ports 设置异常端口 循环等待异常消息   Unix 信号方式 signal(SIGSEGV, signalHandl">
<meta property="og:type" content="article">
<meta property="og:title" content="iOS程序崩溃抓获与分析">
<meta property="og:url" content="https://wangkejie.gitee.io/blogwebpage/iOS/crashreport/crashanalysis.html">
<meta property="og:site_name" content="王科杰">
<meta property="og:description" content="iOS App程序崩溃的抓取与分析 备用: xun开源代码地址   Mach异常捕获方式 mach_port_allocate 创建一场端口 mach_port_insert_right 申请 set_exception_ports 的权限 xxx_set_exception_ports 设置异常端口 循环等待异常消息   Unix 信号方式 signal(SIGSEGV, signalHandl">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wangkejie.gitee.io/blogwebpage/images/iOS/exception_handler.png">
<meta property="article:published_time" content="2019-07-15T03:26:39.000Z">
<meta property="article:modified_time" content="2021-06-25T08:55:53.142Z">
<meta property="article:author" content="Jack Wang">
<meta property="article:tag" content="iOS崩溃">
<meta property="article:tag" content="iOS Crash Grab">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wangkejie.gitee.io/blogwebpage/images/iOS/exception_handler.png">

<link rel="canonical" href="https://wangkejie.gitee.io/blogwebpage/iOS/crashreport/crashanalysis.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>iOS程序崩溃抓获与分析 | 王科杰</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?93e26277de0cf2c5851167f2c6dcaa7d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blogwebpage/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">王科杰</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Jack's Notes</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blogwebpage/" rel="section"><i class="home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blogwebpage/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">52</span></a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blogwebpage/me/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blogwebpage/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">54</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blogwebpage/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">56</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/crashreport/crashanalysis.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          iOS程序崩溃抓获与分析
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-07-15 11:26:39" itemprop="dateCreated datePublished" datetime="2019-07-15T11:26:39+08:00">2019-07-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/iOS-Crash-Grab/" itemprop="url" rel="index"><span itemprop="name">iOS Crash Grab</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="iOS-App程序崩溃的抓取与分析"><a href="#iOS-App程序崩溃的抓取与分析" class="headerlink" title="iOS App程序崩溃的抓取与分析"></a>iOS App程序崩溃的抓取与分析</h1><blockquote>
<p>备用: <span class="exturl" data-url="aHR0cHM6Ly9vcGVuc291cmNlLmFwcGxlLmNvbS90YXJiYWxscy94bnUv">xun开源代码地址<i class="fa fa-external-link-alt"></i></span></p>
</blockquote>
<ol>
<li>Mach异常捕获方式<ul>
<li>mach_port_allocate 创建一场端口</li>
<li>mach_port_insert_right 申请 set_exception_ports 的权限</li>
<li>xxx_set_exception_ports 设置异常端口</li>
<li>循环等待异常消息</li>
</ul>
</li>
<li>Unix 信号方式 signal(SIGSEGV, signalHandler)<ul>
<li>除了OC层面的异常捕捉之外，很多内存错误、访问错误的地址产生的crash则需要利用unix标准的signal机制，注册SIGABRT, SIGBUS, SIGSEGV等信号发生时的处理函数。该函数中我们可以输出栈信息，版本信息等其他一切我们所想要的。</li>
</ul>
</li>
<li>Mach异常 + Unix信号方式<ul>
<li>某个NSException导致程序Crash的，只有拿到这个NSException，获取它的reason，name，callStackSymbols信息才能确定出问题的程序位置。</li>
<li>方法很简单，可通过注册NSUncaughtExceptionHandler捕获异常信息<figure class="highlight csharp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">my_uncaught_exception_handler</span> (<span class="params">NSException *exception</span>)</span> &#123;</span><br><span class="line">    <span class="comment">//这里可以取到 NSException 信息</span></span><br><span class="line">&#125;</span><br><span class="line">NSSetUncaughtExceptionHandler(&amp;my_uncaught_exception_handler);</span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ol>
<h2 id="多个-Crash-日志收集服务共存"><a href="#多个-Crash-日志收集服务共存" class="headerlink" title="多个 Crash 日志收集服务共存"></a>多个 Crash 日志收集服务共存</h2><ul>
<li>拒绝传递 UncaughtExceptionHandler</li>
<li>开发测试阶段，可以利用 fishhook 框架去hookNSSetUncaughtExceptionHandler方法,这样就可以清晰的看到handler的传递流程断在哪里，快速定位污染环境者。</li>
<li>Mach异常端口换出+信号处理Handler覆盖</li>
<li>影响系统崩溃日志准确性<ul>
<li>若程序因NSException而Crash，系统日志中的Last Exception Backtrace信息是完整准确的，不会受应用层的胡来而影响，可作为排查问题的参考线索。</li>
</ul>
</li>
</ul>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>Mach: 微内核，负责操作系统中基本职责：进程和线程抽象、虚拟内存管理、任务调度、进程间通信和消息传递机制。</p>
<p>大家熟知的NSSetUncaughtExceptionHandler() + signal() / sigaction()的方式收集Crash,但是stack overflow并不能被此方法扑捉到;</p>
<p>通常我们所说的异常，一般是有处理器陷阱引发的,通用的Mach异常处理程序exception_triage()，负责将异常转换成Mach 消息。exception_triage()通过调用exception_deliver()尝试把异常投递到thread、task最后是host。首先尝试将异常抛给thread端口，然后尝试抛给task端口，最后再抛给host端口(默认端口)，如果没有一个端口返回KERN_SUCCESS，那么任务就会被终止。</p>
<blockquote>
<p>代码太多，不再贴了，自行下载源码，找到 osfmk/kern/exception.c 文件。 里面有<code>exception_triage()和exception_deliver()函数</code>。关于<code>Exception</code>的相关定义，可以在<code>osfmk/mach/exception_types.h</code>里面查看。下面只贴伪代码</p>
</blockquote>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 位于 osfmk/kern/exception.c</span></span><br><span class="line"><span class="keyword">kern_return_t</span></span><br><span class="line">xception_triage(</span><br><span class="line">    <span class="keyword">exception_type_t</span> exception,</span><br><span class="line">    <span class="keyword">mach_exception_data_t</span> code,</span><br><span class="line">    <span class="keyword">mach_msg_type_number_t</span> codeCnt</span><br><span class="line">)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">thread_t</span> thread;</span><br><span class="line">    <span class="keyword">task_t</span> task;</span><br><span class="line">    <span class="keyword">host_priv_t</span> host_priv;</span><br><span class="line">    <span class="keyword">lck_mtx_t</span> *mutex;</span><br><span class="line">    <span class="keyword">kern_return_t</span> kr = KERN_FAILURE;</span><br><span class="line">    assert(exception != EXC_RPC_ALERT);</span><br><span class="line">    <span class="keyword">if</span> (panic_on_exception_triage) &#123;</span><br><span class="line">        panic(<span class="string">&quot;called exception_triage when it was forbidden by the boot environment&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    thread = current_thread();</span><br><span class="line">        </span><br><span class="line">    <span class="comment">// ================ 分别尝试把异常投递到thread、task最后是host。================</span></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">     * Try to raise the exception at the activation level.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    mutex = &amp;thread-&gt;mutex;</span><br><span class="line">    <span class="keyword">if</span> (KERN_SUCCESS == check_exc_receiver_dependency(exception, thread-&gt;exc_actions, mutex))</span><br><span class="line">    &#123;</span><br><span class="line">        kr = exception_deliver(thread, exception, code, codeCnt, thread-&gt;exc_actions, mutex);</span><br><span class="line">        <span class="keyword">if</span> (kr == KERN_SUCCESS || kr == MACH_RCV_PORT_DIED)</span><br><span class="line">            <span class="keyword">goto</span> out;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">     * Maybe the task level will handle it.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    task = current_task();</span><br><span class="line">    mutex = &amp;task-&gt;lock;</span><br><span class="line">    <span class="keyword">if</span> (KERN_SUCCESS == check_exc_receiver_dependency(exception, task-&gt;exc_actions, mutex))</span><br><span class="line">    &#123;</span><br><span class="line">        kr = exception_deliver(thread, exception, code, codeCnt, task-&gt;exc_actions, mutex);</span><br><span class="line">        <span class="keyword">if</span> (kr == KERN_SUCCESS || kr == MACH_RCV_PORT_DIED)</span><br><span class="line">            <span class="keyword">goto</span> out;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*</span></span><br><span class="line"><span class="comment">     * How about at the host level?</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    host_priv = host_priv_self();</span><br><span class="line">    mutex = &amp;host_priv-&gt;lock;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (KERN_SUCCESS == check_exc_receiver_dependency(exception, host_priv-&gt;exc_actions, mutex))</span><br><span class="line">    &#123;</span><br><span class="line">        kr = exception_deliver(thread, exception, code, codeCnt, host_priv-&gt;exc_actions, mutex);</span><br><span class="line">        <span class="keyword">if</span> (kr == KERN_SUCCESS || kr == MACH_RCV_PORT_DIED)</span><br><span class="line">            <span class="keyword">goto</span> out;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">out:</span><br><span class="line">    <span class="keyword">if</span> ((exception != EXC_CRASH) &amp;&amp; (exception != EXC_RESOURCE) &amp;&amp;</span><br><span class="line">        (exception != EXC_GUARD) &amp;&amp; (exception != EXC_CORPSE_NOTIFY))</span><br><span class="line">        thread_exception_return();</span><br><span class="line">    <span class="keyword">return</span> kr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 位于 osfmk/kern/exception.c</span></span><br><span class="line"><span class="keyword">kern_return_t</span></span><br><span class="line">exception_deliver(</span><br><span class="line">    <span class="keyword">thread_t</span>        thread,</span><br><span class="line">    <span class="keyword">exception_type_t</span>    exception,</span><br><span class="line">    <span class="keyword">mach_exception_data_t</span>   code,</span><br><span class="line">    <span class="keyword">mach_msg_type_number_t</span>  codeCnt,</span><br><span class="line">    struct exception_action *excp,</span><br><span class="line">    <span class="keyword">lck_mtx_t</span>           *mutex)</span><br><span class="line">&#123;</span><br><span class="line">    ...  <span class="comment">// 省略部分代码</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">switch</span> (behavior) &#123;</span><br><span class="line">        <span class="keyword">case</span> EXCEPTION_STATE: &#123;</span><br><span class="line">            <span class="keyword">mach_msg_type_number_t</span> state_cnt;</span><br><span class="line">            <span class="keyword">thread_state_data_t</span> state;</span><br><span class="line">            </span><br><span class="line">            c_thr_exc_raise_state++;</span><br><span class="line">            state_cnt = _MachineStateCount[flavor];</span><br><span class="line">            kr = thread_getstatus(thread, flavor,</span><br><span class="line">                                  (<span class="keyword">thread_state_t</span>)state,</span><br><span class="line">                                  &amp;state_cnt);</span><br><span class="line">            <span class="keyword">if</span> (kr == KERN_SUCCESS) &#123;</span><br><span class="line">                <span class="keyword">if</span> (code64) &#123;</span><br><span class="line">                    kr = mach_exception_raise_state(exc_port,</span><br><span class="line">                                                    exception,</span><br><span class="line">                                                    code,</span><br><span class="line">                                                    codeCnt,</span><br><span class="line">                                                    &amp;flavor,</span><br><span class="line">                                                    state, state_cnt,</span><br><span class="line">                                                    state, &amp;state_cnt);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    kr = exception_raise_state(exc_port, exception,</span><br><span class="line">                                               small_code,</span><br><span class="line">                                               codeCnt,</span><br><span class="line">                                               &amp;flavor,</span><br><span class="line">                                               state, state_cnt,</span><br><span class="line">                                               state, &amp;state_cnt);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (kr == MACH_MSG_SUCCESS &amp;&amp; exception != EXC_CORPSE_NOTIFY)</span><br><span class="line">                    kr = thread_setstatus(thread, flavor,</span><br><span class="line">                                          (<span class="keyword">thread_state_t</span>)state,</span><br><span class="line">                                          state_cnt);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> kr;</span><br><span class="line">        &#125;</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">case</span> EXCEPTION_DEFAULT:</span><br><span class="line">            c_thr_exc_raise++;</span><br><span class="line">            <span class="keyword">if</span> (code64) &#123;</span><br><span class="line">                kr = mach_exception_raise(exc_port,</span><br><span class="line">                                          retrieve_thread_self_fast(thread),</span><br><span class="line">                                          retrieve_task_self_fast(thread-&gt;task),</span><br><span class="line">                                          exception,</span><br><span class="line">                                          code,</span><br><span class="line">                                          codeCnt);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                kr = exception_raise(exc_port,</span><br><span class="line">                                     retrieve_thread_self_fast(thread),</span><br><span class="line">                                     retrieve_task_self_fast(thread-&gt;task),</span><br><span class="line">                                     exception,</span><br><span class="line">                                     small_code, </span><br><span class="line">                                     codeCnt);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> kr;</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">case</span> EXCEPTION_STATE_IDENTITY: &#123;</span><br><span class="line">            <span class="keyword">mach_msg_type_number_t</span> state_cnt;</span><br><span class="line">            <span class="keyword">thread_state_data_t</span> state;</span><br><span class="line">            </span><br><span class="line">            c_thr_exc_raise_state_id++;</span><br><span class="line">            state_cnt = _MachineStateCount[flavor];</span><br><span class="line">            kr = thread_getstatus(thread, flavor,</span><br><span class="line">                                  (<span class="keyword">thread_state_t</span>)state,</span><br><span class="line">                                  &amp;state_cnt);</span><br><span class="line">            <span class="keyword">if</span> (kr == KERN_SUCCESS) &#123;</span><br><span class="line">                <span class="keyword">if</span> (code64) &#123;</span><br><span class="line">                    kr = mach_exception_raise_state_identity(exc_port,</span><br><span class="line">                                                             retrieve_thread_self_fast(thread),</span><br><span class="line">                                                             retrieve_task_self_fast(thread-&gt;task),</span><br><span class="line">                                                             exception,</span><br><span class="line">                                                             code, </span><br><span class="line">                                                             codeCnt,</span><br><span class="line">                                                             &amp;flavor,</span><br><span class="line">                                                             state, state_cnt,</span><br><span class="line">                                                             state, &amp;state_cnt);</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    kr = exception_raise_state_identity(exc_port,</span><br><span class="line">                                                        retrieve_thread_self_fast(thread),</span><br><span class="line">                                                        retrieve_task_self_fast(thread-&gt;task),</span><br><span class="line">                                                        exception,</span><br><span class="line">                                                        small_code, </span><br><span class="line">                                                        codeCnt,</span><br><span class="line">                                                        &amp;flavor,</span><br><span class="line">                                                        state, state_cnt,</span><br><span class="line">                                                        state, &amp;state_cnt);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">if</span> (kr == MACH_MSG_SUCCESS &amp;&amp; exception != EXC_CORPSE_NOTIFY)</span><br><span class="line">                    kr = thread_setstatus(thread, flavor,</span><br><span class="line">                                          (<span class="keyword">thread_state_t</span>)state,</span><br><span class="line">                                          state_cnt);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> kr;</span><br><span class="line">        &#125;</span><br><span class="line">            </span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            panic (<span class="string">&quot;bad exception behavior!&quot;</span>);</span><br><span class="line">            <span class="keyword">return</span> KERN_FAILURE; </span><br><span class="line">    &#125;<span class="comment">/* switch */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>当第一个BSD进程调用bsdinit_task()函数(<code>源码位于bsd/kern/bsd_init.c</code>)启动时，这函数还调用了ux_handler_init()函数(<code>位于bsd/uxkern/ux_exception.c</code>)设置了一个Mach内核线程跑ux_handler()的。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 位于bsd/kern/bsd_init.c</span></span><br><span class="line"><span class="comment">/* Called with kernel funnel held */</span></span><br><span class="line"><span class="keyword">void</span></span><br><span class="line">bsdinit_task(<span class="keyword">void</span>)</span><br><span class="line">&#123;</span><br><span class="line"><span class="comment">//  ...省略</span></span><br><span class="line"></span><br><span class="line">  ux_handler_init(); <span class="comment">// 初始化handler</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 设置port</span></span><br><span class="line">  thread = current_thread();</span><br><span class="line">  (<span class="keyword">void</span>) host_set_exception_ports(host_priv_self(),</span><br><span class="line">     EXC_MASK_ALL &amp; ~(EXC_MASK_RPC_ALERT),<span class="comment">//pilotfish (shark) needs this port</span></span><br><span class="line">     (<span class="keyword">mach_port_t</span>) ux_exception_port,</span><br><span class="line">     EXCEPTION_DEFAULT| MACH_EXCEPTION_CODES,</span><br><span class="line">     <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  ut = (<span class="keyword">uthread_t</span>)get_bsdthread_info(thread);</span><br><span class="line"></span><br><span class="line">  bsd_init_task = get_threadtask(thread);</span><br><span class="line">  init_task_failure_data[<span class="number">0</span>] = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">if</span> CONFIG_MACF</span></span><br><span class="line">  mac_cred_label_associate_user(p-&gt;p_ucred);</span><br><span class="line">  mac_task_label_update_cred (p-&gt;p_ucred, (struct task *) p-&gt;task);</span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br><span class="line">  load_init_program(p);</span><br><span class="line">  lock_trace = <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>每一个thread、task及host自身都有一个异常端口数组，通过调用xxx_set_exception_ports()（xxx为thread、task或host）可以设置这些异常端口。 xxx_set_exception_ports()第四个参数为exception_behavior_t behavior，这将会使用到与行为相匹配的实现（exc.defs 或  mach_exc.defs）。<br>各种行为都在host层被catch_[mach]_exception_xxx处理，64位的对应的是有mach函数(可在/bsd/uxkern/ux_exception.c查看)。<br>这些函数通过调用ux_exception()将异常转换为对应的UNIX信号，并通过threadsignal()将信号投递到出错线程。</p>
<p>所以，如果异常是栈溢出，那么signal是SIGSEGV而不是SIGBUS；如果进程退出了或者线程/进程未准备好处理signal，所注册的signal()是无法接收信号的。</p>
<img src="/blogwebpage/images/iOS/exception_handler.png" class="" title="exception_handler">

<p>把Mach exception 和 UNIX signal 的转换制表后，如下</p>
<table>
<thead>
<tr>
<th>exception type</th>
<th>signal</th>
</tr>
</thead>
<tbody><tr>
<td>EXC_BAD_ACCESS</td>
<td>1、SIGSEGV (KERN_INVALID_ADDRESS)  <br>  2、SIGBUS(其它)</td>
</tr>
<tr>
<td>EXC_BAD_INSTRUCTION</td>
<td>SIGILL</td>
</tr>
<tr>
<td>EXC_ARITHMETIC</td>
<td>SIGFPE</td>
</tr>
<tr>
<td>EXC_EMULATION</td>
<td>SIGEMT</td>
</tr>
<tr>
<td>EXC_SOFTWARE</td>
<td>1、SIGSYS(EXC_UNIX_BAD_SYSCALL) <br> 2、SIGPIPE(EXC_UNIX_BAD_PIPE) <br> 3、SIGABRT(EXC_UNIX_ABORT) <br> 4、SIGKILL(EXC_SOFT_SIGNAL)</td>
</tr>
<tr>
<td>EXC_BREAKPOINT</td>
<td>SIGTRAP ()</td>
</tr>
</tbody></table>
<h2 id="实战"><a href="#实战" class="headerlink" title="实战"></a>实战</h2><p>在Mach中，异常是通过内核中的主要设施-消息传递机制-进行处理的。一个异常与一条消息并无差别，由出错的线程或任务（通过 msg_send()）发送，并通过一个处理程（通过 msg_recv()）接收。<br>由于Mach的异常以消息机制处理而不是通过函数调用，exception messages可以被转发到先前注册的Mach exception处理程序。这意味着你可以插入一个exception处理程序，而不干扰现有的无论是调试器或Apple’s crash reporter。可以使用mach_msg() // flag MACH_SEND_MSG发送原始消息到以前注册的处理程序的Mach端口，将消息转发到一个现有的处理程序。</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">catchMACHExceptions</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">kern_return_t</span> rc = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">exception_mask_t</span> excMask = EXC_MASK_BAD_ACCESS |</span><br><span class="line">    EXC_MASK_BAD_INSTRUCTION |</span><br><span class="line">    EXC_MASK_ARITHMETIC |</span><br><span class="line">    EXC_MASK_SOFTWARE |</span><br><span class="line">    EXC_MASK_BREAKPOINT;</span><br><span class="line">    </span><br><span class="line">    rc = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &amp;myExceptionPort);</span><br><span class="line">    <span class="keyword">if</span> (rc != KERN_SUCCESS) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;-------&gt;Fail to allocate exception port\\\\\\\\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    rc = mach_port_insert_right(mach_task_self(), myExceptionPort, myExceptionPort, MACH_MSG_TYPE_MAKE_SEND);</span><br><span class="line">    <span class="keyword">if</span> (rc != KERN_SUCCESS) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;--------&gt;Fail to insert right&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    rc = thread_set_exception_ports(mach_thread_self(), excMask, myExceptionPort, EXCEPTION_DEFAULT, MACHINE_THREAD_STATE);</span><br><span class="line">    <span class="keyword">if</span> (rc != KERN_SUCCESS) &#123;</span><br><span class="line">        <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;--------&gt;Fail to  set exception\\\\\\\\n&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// at the end of catchMachExceptions, spawn the exception handling thread</span></span><br><span class="line">    <span class="keyword">pthread_t</span> thread;</span><br><span class="line">    pthread_create(&amp;thread, <span class="literal">NULL</span>, exc_handler, <span class="literal">NULL</span>);</span><br><span class="line">&#125; <span class="comment">// end catchMACHExceptions</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> *<span class="title">exc_handler</span><span class="params">(<span class="keyword">void</span> *ignored)</span> </span>&#123;</span><br><span class="line">    <span class="comment">// Exception handler – runs a message loop. Refactored into a standalone function</span></span><br><span class="line">    <span class="comment">// so as to allow easy insertion into a thread (can be in same program or different)</span></span><br><span class="line">    <span class="keyword">mach_msg_return_t</span> rc;</span><br><span class="line">    <span class="built_in">fprintf</span>(<span class="built_in">stderr</span>, <span class="string">&quot;Exc handler listening\\\\\\\\n&quot;</span>);</span><br><span class="line">    <span class="comment">// The exception message, straight from mach/exc.defs (following MIG processing) // copied here for ease of reference.</span></span><br><span class="line">    <span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> &#123;</span></span><br><span class="line">        <span class="keyword">mach_msg_header_t</span> Head;</span><br><span class="line">        <span class="comment">/* start of the kernel processed data */</span></span><br><span class="line">        <span class="keyword">mach_msg_body_t</span> msgh_body;</span><br><span class="line">        <span class="keyword">mach_msg_port_descriptor_t</span> thread;</span><br><span class="line">        <span class="keyword">mach_msg_port_descriptor_t</span> task;</span><br><span class="line">        <span class="comment">/* end of the kernel processed data */</span></span><br><span class="line">        NDR_record_t NDR;</span><br><span class="line">        <span class="keyword">exception_type_t</span> exception;</span><br><span class="line">        <span class="keyword">mach_msg_type_number_t</span> codeCnt;</span><br><span class="line">        <span class="keyword">integer_t</span> code[<span class="number">2</span>];</span><br><span class="line">        <span class="keyword">int</span> flavor;</span><br><span class="line">        <span class="keyword">mach_msg_type_number_t</span> old_stateCnt;</span><br><span class="line">        <span class="keyword">natural_t</span> old_state[<span class="number">144</span>];</span><br><span class="line">    &#125; Request;</span><br><span class="line">    </span><br><span class="line">    Request exc;</span><br><span class="line"></span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">rep_msg</span> &#123;</span></span><br><span class="line">        <span class="keyword">mach_msg_header_t</span> Head;</span><br><span class="line">        NDR_record_t NDR;</span><br><span class="line">        <span class="keyword">kern_return_t</span> RetCode;</span><br><span class="line">    &#125; rep_msg;</span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        <span class="comment">// Message Loop: Block indefinitely until we get a message, which has to be</span></span><br><span class="line">        <span class="comment">// 这里会阻塞，直到接收到exception message，或者线程被中断。</span></span><br><span class="line">        <span class="comment">// an exception message (nothing else arrives on an exception port)</span></span><br><span class="line">        rc = mach_msg( &amp;exc.Head,</span><br><span class="line">                      MACH_RCV_MSG|MACH_RCV_LARGE,</span><br><span class="line">                      <span class="number">0</span>,</span><br><span class="line">                      <span class="keyword">sizeof</span>(Request),</span><br><span class="line">                      myExceptionPort, <span class="comment">// Remember this was global – that&#x27;s why.</span></span><br><span class="line">                      MACH_MSG_TIMEOUT_NONE,</span><br><span class="line">                      MACH_PORT_NULL);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span>(rc != MACH_MSG_SUCCESS) &#123;</span><br><span class="line">            <span class="comment">/*... */</span></span><br><span class="line">            <span class="keyword">break</span> ;</span><br><span class="line">        &#125;;</span><br><span class="line"></span><br><span class="line">         <span class="comment">// Normally we would call exc_server or other. In this example, however, we wish</span></span><br><span class="line">        <span class="comment">// to demonstrate the message contents:</span></span><br><span class="line">        </span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;Got message %d. Exception : %d Flavor: %d. Code %lld/%lld. State count is %d\\\\\\\\n&quot;</span> ,</span><br><span class="line">               exc.Head.msgh_id, exc.exception, exc.flavor,</span><br><span class="line">               exc.code[<span class="number">0</span>], exc.code[<span class="number">1</span>], <span class="comment">// can also print as 64-bit quantity</span></span><br><span class="line">               exc.old_stateCnt);</span><br><span class="line">        </span><br><span class="line">        rep_msg.Head = exc.Head;</span><br><span class="line">        rep_msg.NDR = exc.NDR;</span><br><span class="line">        rep_msg.RetCode = KERN_FAILURE;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">kern_return_t</span> result;</span><br><span class="line">        <span class="keyword">if</span> (rc == MACH_MSG_SUCCESS) &#123;</span><br><span class="line">            result = mach_msg(&amp;rep_msg.Head,</span><br><span class="line">                              MACH_SEND_MSG,</span><br><span class="line">                              <span class="keyword">sizeof</span> (rep_msg),</span><br><span class="line">                              <span class="number">0</span>,</span><br><span class="line">                              MACH_PORT_NULL,</span><br><span class="line">                              MACH_MSG_TIMEOUT_NONE,</span><br><span class="line">                              MACH_PORT_NULL);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span>  <span class="literal">NULL</span>;</span><br><span class="line">    </span><br><span class="line">&#125; <span class="comment">// end exc_handler</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>接下来，我们测试一下。</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="built_in">void</span>)test</span><br><span class="line">&#123;</span><br><span class="line"><span class="string">    [self test]</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>结果如下:</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Exc handler listening</span><br><span class="line">Got message <span class="number">2401.</span> Exception : <span class="number">1</span> Flavor: <span class="number">0.</span> Code <span class="number">2</span>/<span class="number">1486065656.</span> State count <span class="keyword">is</span> <span class="number">8</span></span><br><span class="line">(lldb)</span><br></pre></td></tr></table></figure>

<p>我们可以查看<code>mach/exception_types.h</code> 对exception type的定义</p>
<p>Exception:  1,  即为EXC_BAD_ACCESS<br>code:       2,  即KERN_PROTECTION_FAILURE</p>
<p>而ux_exception() 函数告诉我们Code与signal是怎么转换的。<br>也就是 Exception = EXC_BAD_ACCESS， code = 2 对应的是SIGBUS信号，又因为为是stack overflow，信号应该是SIGSEGV。<br>那么结这个exception就是:</p>
<blockquote>
<p>Exception Type: EXC_BAD_ACCESS (SIGSEGV)<br>Exception Subtype: KERN_PROTECTION_FAILURE</p>
</blockquote>
<p>再试试其他的：</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">int</span> *pi = (<span class="built_in">int</span>*)<span class="number">0x00001111</span>;</span><br><span class="line">*pi = <span class="number">17</span>;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>Exc handler listening<br>Got message 2401. Exception : 1 Flavor: 0. Code 1/4369. State count is 8(lldb) </p>
</blockquote>
<blockquote>
<p>Exception Type: EXC_BAD_ACCESS (SIGSEGV)<br>Exception Subtype: KERN_INVALID_ADDRESS</p>
</blockquote>
<h2 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h2><p>除了上面硬件产生的信号，另外还有软件产生的信号。软件产生的信号来自kill()、pthread_kill()两个函数的调用，大概过程是这样的：kill()/pthread_kill() –&gt; … –&gt; psignal_internal() –&gt; act_set_astbsd()。最终也会调用act_set_astbsd()发送信号到目标线程。这意味着Mach exception流程是不会走的。<br>另外，在abort()源码注释着：<code>&lt;rdar://problem/7397932&gt; abort() should call pthread_kill to deliver a signal to the aborting thread</code> , 它是这样调用的(void)pthread_kill(pthread_self(), SIGABRT);。Apple’s Crash Reporter 把<code>SIGABRT</code>的Mach exception type记为<code>EXC_CRASH</code>，不同与上面转变表。</p>
<blockquote>
<p>Exception Type: EXC_CRASH (SIGABRT)<br>Exception Codes: 0x0000000000000000, 0x0000000000000000</p>
</blockquote>
<p>所以尽管Mach exception handle 比 UNIX signal handle 更有优势，但我们还是须要注册signal handle用于处理EXC_SOFTWARE/EXC_CRASH。</p>
<span id="more"></span>

<h1 id="附"><a href="#附" class="headerlink" title="附"></a>附</h1><p>崩溃日志的字段认识</p>
<ul>
<li>Incident Identifier： 事件标识符，每个crash文件对应一个唯一的标识符。</li>
<li>CrashReporter Key： 匿名设备标识符。</li>
<li>Hardware Model：设备型号；</li>
<li>Process： 进程名；</li>
<li>Identifier：app Identifier；</li>
<li>Exception Type： 异常类型；</li>
<li>Exception Codes： 异常代码；</li>
<li>Termination Reason：进程被结束的原因</li>
</ul>
<p>Crash Reports  (<span class="exturl" data-url="aHR0cHM6Ly9kZXZlbG9wZXIuYXBwbGUuY29tL2xpYnJhcnkvY29udGVudC90ZWNobm90ZXMvdG4yMTUxL19pbmRleC5odG1s">https://developer.apple.com/library/content/technotes/tn2151/_index.html<i class="fa fa-external-link-alt"></i></span>)</p>

    </div>

    
    
    
        <div class="reward-container">
  <div>希望对您有所帮助，您的支持将是我莫大的动力！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/wechatpay.png" alt="Jack Wang 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/alipay.png" alt="Jack Wang 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blogwebpage/tags/iOS%E5%B4%A9%E6%BA%83/" rel="tag"># iOS崩溃</a>
              <a href="/blogwebpage/tags/iOS-Crash-Grab/" rel="tag"># iOS Crash Grab</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blogwebpage/iOS/kernelarchitecture/xnu.html" rel="prev" title="Mach微内核简介">
      <i class="fa fa-chevron-left"></i> Mach微内核简介
    </a></div>
      <div class="post-nav-item">
    <a href="/blogwebpage/llvm/lldb.html" rel="next" title="LLDB">
      LLDB <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#iOS-App%E7%A8%8B%E5%BA%8F%E5%B4%A9%E6%BA%83%E7%9A%84%E6%8A%93%E5%8F%96%E4%B8%8E%E5%88%86%E6%9E%90"><span class="nav-number">1.</span> <span class="nav-text">iOS App程序崩溃的抓取与分析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%A4%9A%E4%B8%AA-Crash-%E6%97%A5%E5%BF%97%E6%94%B6%E9%9B%86%E6%9C%8D%E5%8A%A1%E5%85%B1%E5%AD%98"><span class="nav-number">1.1.</span> <span class="nav-text">多个 Crash 日志收集服务共存</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A6%82%E8%BF%B0"><span class="nav-number">1.2.</span> <span class="nav-text">概述</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9E%E6%88%98"><span class="nav-number">1.3.</span> <span class="nav-text">实战</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%80%E5%90%8E"><span class="nav-number">1.4.</span> <span class="nav-text">最后</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%99%84"><span class="nav-number">2.</span> <span class="nav-text">附</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jack Wang"
      src="/blogwebpage/images/avatar.gif">
  <p class="site-author-name" itemprop="name">Jack Wang</p>
  <div class="site-description" itemprop="description">书山有路勤为径，学海无涯苦作舟！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blogwebpage/archives/">
        
          <span class="site-state-item-count">52</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blogwebpage/categories/">
          
        <span class="site-state-item-count">56</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blogwebpage/tags/">
          
        <span class="site-state-item-count">54</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Jack-Ving"><i class="github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjcyNzg4MTk0NUBxcS5jb20=" title="E-Mail → mailto:727881945@qq.com"><i class="envelope fa-fw"></i>E-Mail</span>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><span class="exturl" data-url="aHR0cHM6Ly9iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备16036665号-2 </span>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jack Wang</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        


  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1277804316&web_id=1277804316"></script>
  </div>






      </div>
    </footer>
  </div>

  
  <script src="/blogwebpage/lib/anime.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.ui.min.js"></script>

<script src="/blogwebpage/js/utils.js"></script>

<script src="/blogwebpage/js/motion.js"></script>


<script src="/blogwebpage/js/schemes/pisces.js"></script>


<script src="/blogwebpage/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/blogwebpage/js/local-search.js"></script>













  

  

</body>
</html>
